package com.example.demo.controller;

import com.example.demo.entity.Order;
import com.example.demo.mapper.OrderMapper;
import com.example.demo.utils.PagingResult;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("/order") // 控制器的前缀地址
public class OrderController {
    @Autowired
    OrderMapper orderMapper;

    /**
     * 获取分页的订单数据
     * @param limit 每页数量
     * @param offset 偏移量
     * @param field 搜索字段
     * @param code 搜索关键词
     * @return 分页结果
     */
    @GetMapping("/list")
    public PagingResult<Order> select(
            @RequestParam(required = false, name = "limit", defaultValue = "10") int limit,
            @RequestParam(required = false, name = "offset", defaultValue = "0") int offset,
            @RequestParam(required = false, name = "field") String field,
            @RequestParam(required = false, name = "code") String code
    ) {
        List<Order> orderList;
        int total;
        
        if (field != null && code != null && !code.isEmpty()) {
            // 带搜索条件的查询
            orderList = orderMapper.findBySearch(offset, limit, field, code);
            total = orderMapper.countBySearch(field, code);
        } else {
            // 不带搜索条件的查询
            orderList = orderMapper.findByPage(offset, limit);
            total = orderMapper.count();
        }
        
        return new PagingResult<Order>(orderList, total);
    }

    /**
     * 根据ID获取订单
     * @param id 订单ID
     * @return 订单对象
     */
    @GetMapping("/{id}")
    public Order getById(@PathVariable("id") int id) {
        return orderMapper.findById(id);
    }

    /**
     * 添加订单
     * @param order 订单对象
     * @return 响应结果
     */
    @PostMapping("/add")
    public int add(@RequestBody Order order) {
        // 设置订单日期为当前时间（如果为空）
        if (order.getOrder_date() == null) {
            order.setOrder_date(new java.sql.Timestamp(System.currentTimeMillis()));
        }
        return orderMapper.insert(order);
    }

    /**
     * 更新订单
     * @param order 订单对象
     * @return 响应结果
     */
    @PutMapping("/update")
    public int update(@RequestBody Order order) {
        return orderMapper.update(order);
    }

    /**
     * 删除订单
     * @param id 订单ID
     * @return 影响行数
     */
    @DeleteMapping("/delete/{id}")
    public int delete(@PathVariable("id") int id) {
        return orderMapper.delete(id);
    }
}